import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'react-toastify';
import './Users.css';

const UserEdit = () => {
  const [formData, setFormData] = useState({
    username: '',
    fullName: '',
    email: '',
    role: ''
  });
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const { id } = useParams();
  const navigate = useNavigate();
  const [originalUsername, setOriginalUsername] = useState('');

  // 获取用户信息
  useEffect(() => {
    const fetchUser = async () => {
      try {
        setLoading(true);
        const res = await axios.get(`/users/${id}`);
        const user = res.data;

        setOriginalUsername(user.username);
        setFormData({
          username: user.username,
          fullName: user.full_name || '',
          email: user.email || '',
          role: user.role
        });
      } catch (err) {
        console.error('获取用户信息失败', err);
        setError('获取用户信息失败，请返回重试');
      } finally {
        setLoading(false);
      }
    };

    fetchUser();
  }, [id]);

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // 表单验证
    if (!formData.username) {
      return toast.error('用户名不能为空');
    }

    setSubmitting(true);
    try {
      // 准备要提交的数据（排除空值）
      const updateData = {};
      if (formData.fullName) updateData.fullName = formData.fullName;
      if (formData.email) updateData.email = formData.email;
      if (formData.role) updateData.role = formData.role;

      // 只有管理员可以修改自己的角色
      const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
      if (originalUsername === 'admin' && currentUser.username !== 'admin') {
        delete updateData.role;
      }

      await axios.put(`/users/${id}`, updateData);
      toast.success('用户信息更新成功');
      navigate('/users');
    } catch (err) {
      console.error('更新用户信息失败', err);
      toast.error(err.response?.data?.message || '更新用户信息失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return <div className="loading">加载用户信息中...</div>;
  }

  if (error) {
    return (
      <div className="user-edit-container">
        <div className="error-message">{error}</div>
        <button className="btn btn-secondary" onClick={() => navigate('/users')}>返回用户列表</button>
      </div>
    );
  }

  return (
    <div className="user-edit-container">
      <h1 className="page-title">编辑用户</h1>

      <form onSubmit={handleSubmit} className="user-form">
        <div className="form-group">
          <label htmlFor="username">用户名</label>
          <input
            type="text"
            id="username"
            name="username"
            value={formData.username}
            onChange={handleChange}
            required
            disabled={originalUsername === 'admin'}
            className="form-control"
          />
          {originalUsername === 'admin' && (
            <small className="form-text">管理员用户名不可修改</small>
          )}
        </div>

        <div className="form-group">
          <label htmlFor="fullName">姓名</label>
          <input
            type="text"
            id="fullName"
            name="fullName"
            value={formData.fullName}
            onChange={handleChange}
            className="form-control"
          />
        </div>

        <div className="form-group">
          <label htmlFor="email">邮箱</label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            className="form-control"
          />
        </div>

        <div className="form-group">
          <label htmlFor="role">角色</label>
          <select
            id="role"
            name="role"
            value={formData.role}
            onChange={handleChange}
            className="form-control"
            disabled={originalUsername === 'admin' && JSON.parse(localStorage.getItem('currentUser') || '{}').username !== 'admin'}
          >
            <option value="admin">管理员</option>
            <option value="payment_manager">清算经理</option>
            <option value="employee">员工</option>
          </select>
          {originalUsername === 'admin' && JSON.parse(localStorage.getItem('currentUser') || '{}').username !== 'admin' && (
            <small className="form-text">只有管理员可以修改管理员角色</small>
          )}
        </div>

        <div className="form-actions">
          <button
            type="submit"
            className="btn btn-primary"
            disabled={submitting}
          >
            {submitting ? '保存中...' : '保存修改'}
          </button>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/users')}
          >
            取消
          </button>
        </div>
      </form>
    </div>
  );
};

export default UserEdit;